from minio import Minio
from minio.error import S3Error
import os
import hashlib
import logging
from typing import Optional

logger = logging.getLogger(__name__)

class MinioUtil:
    def __init__(self):
        self.minio_client = Minio(
            "101.237.129.10:9000",
            access_key="minioadmin",
            secret_key="minioadmin",
            secure=False
        )
        self.bucket_name = "query"
        self.base_url = "http://101.237.129.10:9000/query"

    def upload_file(self, file_data, filename: str) -> Optional[str]:
        """上传文件到 MinIO"""
        try:
            # 确保 bucket 存在
            if not self.minio_client.bucket_exists(self.bucket_name):
                self.minio_client.make_bucket(self.bucket_name)

            # 生成唯一文件名
            file_content = file_data.read()
            file_data.seek(0)
            content_hash = hashlib.md5(file_content).hexdigest()
            file_extension = os.path.splitext(filename)[1].lower()
            unique_filename = f"{content_hash}{file_extension}"

            # 设置文件类型
            content_type_map = {
                '.png': 'image/png',
                '.gif': 'image/gif',
                '.jpg': 'image/jpeg',
                '.jpeg': 'image/jpeg'
            }
            content_type = content_type_map.get(file_extension, 'application/octet-stream')

            # 上传文件
            self.minio_client.put_object(
                bucket_name=self.bucket_name,
                object_name=unique_filename,
                data=file_data,
                length=len(file_content),
                content_type=content_type
            )
            
            url = f"{self.base_url}/{unique_filename}"
            logger.info(f"File uploaded successfully: {url}")
            return url
            
        except Exception as e:
            logger.error(f"Error uploading file: {str(e)}")
            raise

    def get_file_url(self, object_name):
        """Get file URL with enhanced error handling"""
        try:
            if not object_name:
                return None

            # Extract object name from full URL if needed
            if '/' in object_name:
                object_name = object_name.split('/')[-1]
            
            # Verify object exists
            try:
                self.minio_client.stat_object(self.bucket_name, object_name)
            except S3Error as e:
                logging.warning(f"Object {object_name} not found: {str(e)}")
                return None

            return f"{self.base_url}/{object_name}"
        except Exception as e:
            logging.error(f"Error generating URL for {object_name}: {str(e)}")
            return None